import os

import openpyxl
from flask import Flask, request, send_file
from flask_cors import cross_origin
from gevent import pywsgi
import threading

from apps import main
from apps.logger_config import logger
from apps.nacos import service_register, HEARTBEATS_TIME, service_beat, PORT

app = Flask(__name__)


@app.route('/sdtm/generate', methods=['POST', 'GET'])
@cross_origin()
def download_sdtm():
    project_id = request.args.get('projectId')
    print(project_id)
    # 在本地生成的SDTM路径
    # path = "static/" + project_id + ".xlsx"
    path = f"D:/work/cdsp/file/cdiscFile/sdtmFile/{project_id}.xlsx"
    os.makedirs(os.path.dirname(path), exist_ok=True)  # 确保目录存在
    # 如果文件存在，则删除该文件
    if os.path.exists(path):
        os.remove(path)
    try:
        book = openpyxl.Workbook()
        book.save(path)

        # 进行转换操作
        sdtm_path = main.sdtm_convert(project_id, path)

        # 在转换完成后关闭工作簿
        book.close()

        # 返回文件
        return send_file(sdtm_path, as_attachment=True)
    except Exception as e:
        # 处理异常情况
        print(f"An error occurred: {e}")
        if 'book' in locals():
            book.close()
        raise


@app.route('/healthCheck', methods=['POST', 'GET'])
@cross_origin()
def health_check():
    dic = {"status": 200, "message": 'success', "data": 'success'}
    return dic


# 发布http服务，并且注册到nocos
if __name__ == '__main__':

    app.debug = True

    service_register()
    # 5秒以后，异步执行service_beat()方法
    threading.Timer(HEARTBEATS_TIME, service_beat).start()

    server = pywsgi.WSGIServer(('0.0.0.0', PORT), app)
    server.serve_forever()
    logger.info("程序启动")
